<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Oauth</title>
    <script type="text/javascript" th:src="@{/jquery-3.6.0.js}"></script>
</head>
<body>
<div>
    <h1>Oauth</h1>
    <button id="createOrder">创建订单</button>
</div>
</body>
</html>
<script type="text/javascript">
    $(function () {
        // Javascript使用thymeleaf变量
        var code = "[[${param.code}]]";
        console.log("code= " + code)

        // 如果没有接收到code应该是授权不成功、用户取消授权等情况
        if((code == undefined) || (code == null) || (code == "")) {
            console.log("授权失败");
            return;
        }
        $.ajax({
            type:'POST',
            url:'http://localhost:57025/third-party-login',
            // 授权码
            data: {"code": code},
            dataType:'json',
            success:function(result){
                console.log('请求成功！');
                //console.log(result);

                // 清除本地存储
                localStorage.removeItem("shop.userId")
                localStorage.removeItem("shop.nickName")
                localStorage.removeItem("shop.token")
                // 保存用户名到本地存储
                localStorage.setItem("shop.userId", result.data.user.id);
                localStorage.setItem("shop.nickName", result.data.user.nickName);
                // 保存token到本地存储
                localStorage.setItem("shop.token", result.data.token);
            },
            error:function(errordata){
                console.log('请求出错！');
                console.log(errordata);
            }
        })
        $("#createOrder").click(function () {
            $.ajax({
                type:'GET',
                url:'http://localhost:57024/order-service/api/order?productId=1&quantity=1',
                beforeSend : function(xhr) {
                    // 按JWT规范要求，token以Bearer格式放于Authorization头中。
                    // Bearer代表Authorization头定义的schema
                    xhr.setRequestHeader("Authorization", "Bearer " + localStorage.getItem("shop.token"));
                },
                dataType:'json',
                success:function(result){
                    console.log('下单成功！');
                    console.log(result);
                },
                error:function(errordata){
                    console.log('请求出错！');
                    console.log(errordata);
                }
            })
        });
    });
</script>